<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Example</title>
<script type="text/javascript">
    let socket;

    function initWebSocket() {
        // WebSocket URL, replace with your server's WebSocket endpoint
        const wsURL = 'ws://8.137.90.97:2121/ws'; // Replace with actual URL

        socket = new WebSocket(wsURL);

        // Connection opened
        socket.addEventListener('open', onOpen);

        // Listen for messages
        socket.addEventListener('message', onMessage);

        // Listen for errors
        socket.addEventListener('error', onError);

        // Connection closed
        socket.addEventListener('close', onClose);
    }

    function onOpen(event) {
        console.log('Connected to WebSocket server.');

        // Send login message or token here
        const loginData = {
            user_code: 'user',
            user_key: 'user_key', // Replace with actual user data
            server_password: 'myServerPassword'  // Replace with actual user data or use a token instead
        };

        socket.send(JSON.stringify(loginData));
    }

    function onMessage(event) {
        console.log('Message from server ', event.data);

        // Parse the incoming message and handle it accordingly
        try {
            const data = JSON.parse(event.data);
            console.log(data)
            if(data.message == 'Login successful'){
                document.getElementById('status').innerText = '登录成功.';
            }else{
                displayNewMessage(data);
            }
        } catch (e) {
            console.error('Failed to parse message:', e);
        }
    }

    function displayNewMessage(data) {
        const messageContainer = document.getElementById('messages');
        const newMessageElement = document.createElement('div');
        newMessageElement.innerText = `New Message: ${data.message}`;
        messageContainer.appendChild(newMessageElement);
    }

    function onError(event) {
        console.error('WebSocket error observed:', event);
    }

    function onClose(event) {
        console.log('WebSocket connection closed. Trying to reconnect...');
        
        // Optionally, you can check the event.code to determine why the connection was closed
        
        // Attempt to reconnect after a delay
        setTimeout(initWebSocket, 5000); // Retry every 5 seconds
    }

    window.onload = function () {
        initWebSocket();
    };
</script>
</head>
<body>
<h1>WebSocket Chat Example</h1>
<div id="status">Connecting...</div>
<div id="messages"></div>
</body>
</html>